/**
 * 
 */
package com.eagle.coders.rules.service;

import java.util.Collection;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;

import org.drools.KnowledgeBase;
import org.drools.KnowledgeBaseFactory;
import org.drools.builder.KnowledgeBuilder;
import org.drools.builder.KnowledgeBuilderFactory;
import org.drools.builder.ResourceType;
import org.drools.io.ResourceFactory;
import org.drools.runtime.StatefulKnowledgeSession;

import com.eagle.coders.security.beans.dao.annotation.JBossDrools;

/**
 * @author Anees
 * 
 */
@JBossDrools
public class DroolsRuleService implements RuleService {

	private StatefulKnowledgeSession knowledge;

	private Collection<Object> objects;

	StringBuffer strbuff = new StringBuffer();

	@Override
	public void buildRulesEngine(String drlPath, List<?> facts,
			Map<String, Object> globals) {

		final KnowledgeBuilder kbuilder = KnowledgeBuilderFactory
				.newKnowledgeBuilder();

		String url = this.getClass().getClassLoader().getResource(drlPath)
				.getFile();

		kbuilder.add(
				ResourceFactory.newClassPathResource(drlPath, this.getClass()),
				ResourceType.DRL);

		// Resource drlResource = ResourceFactory.newReaderResource(new
		// StringReader(strbuff.toString()));

		KnowledgeBase knbase = KnowledgeBaseFactory.newKnowledgeBase();

		knbase.addKnowledgePackages(kbuilder.getKnowledgePackages());

		knowledge = knbase.newStatefulKnowledgeSession();

		if (null != globals) {

			Set<String> identifiers = globals.keySet();

			for (String identifier : identifiers) {

				knowledge.setGlobal(identifier, globals.get(identifier));
			}
		}

		Iterator<?> iterator = facts.iterator();

		while (iterator.hasNext()) {
			
			Object obj = iterator.next();
			
			knowledge.insert(obj);
		}

//		 knowledge.getAgenda().getAgendaGroup("").setFocus();
		
		knowledge.fireAllRules();

		objects = knowledge.getObjects();

		knowledge.dispose();
	}

	@Override
	public Collection<Object> getObjects() {

		return objects;
	}

}
